/**
 * Copyright (C) 2013 AirChina
 *
 * @className:com.airchina.wechat.util.SerializeUtil
 * @description:
 * 
 * @version:v1.0.0 
 * @author:larry
 * 
 * Modification History:
 * NO   Date         Author      Version     Description
 * -----------------------------------------------------------------
 *     2013-10-21     larry       v1.0.0        create
 *
 *
 */
package com.china.itapi.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

/**
 * @Description:
 * @author:larry
 * @version:v1.0.0
 * @Created:2013-10-21下午4:23:53
 * @Modified:
 */
public class SerializeUtil {

	private static final Logger log = LoggerFactory.getLogger(SerializeUtil.class);

	private static Gson gson = new Gson();

	public static String serializeJson(Object bean) {
		return gson.toJson(bean);
	}

	public static <T> T deSerializeJson(String json, Class<T> clazz) {
		return gson.fromJson(json, clazz);
	}

	/**
	 * 序列化
	 */
	public static byte[] serialize(Serializable object, boolean gzip) {
		ObjectOutputStream oos = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			if (gzip) {
				oos = new ObjectOutputStream(new GZIPOutputStream(baos));
			} else {
				oos = new ObjectOutputStream(baos);
			}
			oos.writeObject(object);
			oos.close();
			return baos.toByteArray();
		} catch (Exception e) {
			log.error("serialize error", e);
		} finally{
			if(oos != null){
				try {
					oos.close();
				} catch (IOException e) {}
			}
		}
		return null;
	}

	/**
	 * 反序列化
	 */
	public static Object deSerialize(byte[] bytes, boolean gzip) {
		ObjectInputStream ois = null;
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
			if (gzip) {
				ois = new ObjectInputStream(new GZIPInputStream(bais));
			} else {
				ois = new ObjectInputStream(bais);
			}
			return ois.readObject();
		} catch (Exception e) {
			log.error("unserialize error", e);
		} finally{
			if(ois != null){
				try {
					ois.close();
				} catch (IOException e) {}
			}
		}
		return null;
	}
}
